package cn.xiaye.httpserver.action;

import java.util.HashMap;

import cn.xiaye.httpserver.Constant;
import cn.xiaye.httpserver.Request;
import cn.xiaye.httpserver.Response;

/**
 * 操作集合
 * 
 * @author 王夏夜
 * 
 */
public abstract class DefaultListAction {
	/**
	 * 所有动作集合
	 */
	public static HashMap<String, DefaultListAction> actions = new HashMap<String, DefaultListAction>();

	/**
	 * 固定子类添加过程
	 */
	private static void initActionList() {
		if (actions.size() != 0) {
			return;
		}
		/** action集合 */
		actions.put("/login.do", new LoginAction());
		actions.put("/test.do", new TestAction());

	}

	/**
	 * 所有Action操作集合 此类将request response 分别分发给各个子类 子类进行操作
	 * 
	 * @param request
	 * @param response
	 */
	public static void doService(Request request, Response response) {
		if (request.getAction().matches(Constant.URL_PATTEN)) {
			/** 处理以.do为结尾的Action */
			initActionList();
			DefaultListAction action = actions.get(request.getAction());
			if (action == null) {
				throw new RuntimeException("can not find the action :" + request.getAction());
			}
			String template = action.execute(request, response);
			
			if (template != null) {
				response.responseFile(template);
			}
			
		} else if (request.getAction().equals("/")) {
			response.responseFile(Constant.DEFAULT_INDEX_FILE);
		} else {
			response.responseFile(request.getAction());
		}
	}

	/**
	 * 子类需重写
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public abstract String execute(Request request, Response response);
}
